package ldh.maker.freemaker;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;
import ldh.maker.util.FreeMakerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public abstract class FreeMarkerMaker<T> extends Maker<T> {

	protected Configuration cfg = new Configuration();

	protected Logger logger = LoggerFactory.getLogger(FreeMarkerMaker.class);

	protected Map<Object, Object> data = new HashMap<Object, Object>();

	protected String ftl;

	public abstract void data();

	public FreeMarkerMaker() {
		BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel fileStatics;
		try {
			fileStatics = (TemplateHashModel) staticModels.get(FreeMakerUtil.class.getName());
			cfg.setSharedVariable("util", fileStatics);
			cfg.setDefaultEncoding("UTF-8");
			String ftlPath = FreeMarkerMaker.class.getResource("/ftl/mapper.ftl").getPath();
//			cfg.setDirectoryForTemplateLoading(file.getParentFile());
			cfg.setClassForTemplateLoading(FreeMarkerMaker.class, "/ftl");
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			logger.error("freemaker init error!!!!!!!!!!!!1", e);
			e.printStackTrace();
		}

	}

	protected String toString(String ftl, Map<Object, Object> root) {
		try {
			StringWriter writer = new StringWriter();
			Template temp = cfg.getTemplate(ftl);
			temp.process(root, writer);
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return "";
	}

	protected void out(String ftl, Map<Object, Object> root) {
		OutputStream out = null;
		try {
			check(outPath);
			out = new FileOutputStream(new File(outPath, fileName));
//			Writer writer = new OutputStreamWriter(out);
			OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
			Template temp = cfg.getTemplate(ftl);
	        temp.process(root, writer);
	        writer.flush();
	        writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public T ftl(String ftl) {
		this.ftl = ftl;
		return ((T) this);
	}

	public T put(String key, Object value) {
		data.put(key, value);
		return ((T) this);
	}

	private void check(String path) {
		File f = new File(path);
		while(!f.exists()) {
			f.mkdirs();
		}
	}
}
